<?php
class CacheClass {
	
	/*
	 * Author:http://antirez.com
	 * Crea funzioni cacheate per il caricamento della pagina
	 */
	public static function memofunction($name,$arglist,$body) 
	{
	    $prefix = "
	    \$__self = '__FUNCNAME__';
	    global \$__memo;
	    global \$__flag;
	    if (!isset(\$__memo)) {
	        \$__memo = Array();
	        \$__flag = Array();
	    }
	    \$__argv = func_get_args();
	    \$__argc = count(\$__argv);
	    \$__aux = '[\$__self]';
	    \$__aux2 = '';
	    for(\$__i = 0; \$__i < \$__argc; \$__i++) {
	        \$__aux .= '[\$__argv['.\$__i.']]';
	        \$__aux2 .= '\$__argv['.\$__i.'],';
	    }
	    \$__aux2 = trim(\$__aux2,',');
	    \$__issetmemo = eval('return isset(\$__memo'.\$__aux.');');
	    \$__issetflag = eval('return isset(\$__flag'.\$__aux.');');
	    if (!\$__issetflag) {
	        if (!\$__issetmemo) {
	            eval('\$__flag'.\$__aux.'=true;');
	            \$__retval = eval('return '.\$__self.'('.\$__aux2.');');
	            eval('unset(\$__flag'.\$__aux.');');
	            eval('\$__memo'.\$__aux.'=\$__retval;');
	        }
	        return eval('return \$__memo'.\$__aux.';');
	    }"."\n";
	    $body = str_replace("__FUNCNAME__",$name,$prefix).$body;
	    eval('function '.$name.' ('.$arglist.') {'.$body.'}');
	}
	
	/**
	 * Crea una cache per la funzione e ritorna direttamente il risultato
	 * @param: $function
	 */
	public static function cachevar ($function_name,$arg,$sec)
	{
		$tmp_lastmod = 0;
		$tmp_lastmod = @filemtime(APP_PATH.DS.'caching'.DS.md5($function_name.$arg));
		
		if ($tmp_lastmod && (time()-$tmp_lastmod)<$sec)
    	{
    		$_MEMOIZE = unserialize(base64_decode(file_get_contents(APP_PATH.DS.'caching'.DS.md5($function_name.$arg))));
		}
		else
		{
			$_MEMOIZE = eval('return '.$function_name.'('.$arg.');');
			file_put_contents((string)APP_PATH.DS.'caching'.DS.md5($function_name.$arg), base64_encode(serialize($_MEMOIZE)));
		}
		
    	return $_MEMOIZE;
	}
}
?>